<template>
  <view class="container">
    <view v-if="hasCameraError" class="error-message">未找到摄像头，请检查权限或设备。</view>
    <view v-else-if="cameraing" class="camera-container">
      <camera class="camera" device-position="front" @error="handleError" />
      <view class="circle-overlay"></view>
    </view>
    <view v-else class="photo-container">
      <image class="photo" :src="photoPath" mode="aspectFit" />
    </view>
    <button class="my-but-primary" @click="capture" v-if="cameraing&&!hasCameraError">确认拍照</button>
	<button class="my-but-primary" @click="uploadPhoto" v-if="!cameraing" :disabled="uploading">确定上传</button>
    <button class="secondary-but" @click="retakePhoto" v-if="!cameraing" :disabled="uploading">重新拍照</button>
    <button class="secondary-but" @click="close" v-if="cameraing">关闭拍照</button>
  </view>
</template>

<script>
import $file from '@/common/file.js';
export default {
  props: {
  },
  data() {
    return {
      hasCameraError: false,	//摄像头是否正常
      photoPath: '',
      cameraing: true, 			// 是否拍照中
	  uploading:false 			// 是否正在上传
    };
  },
  methods: {
	// 处理摄像头错误
    handleError(e) {
      console.error('Camera error: ', e.detail);
      this.hasCameraError = true;
    },
	// 拍照
    capture() {
      const ctx = uni.createCameraContext();
      ctx.takePhoto({
        quality: 'high',
        success: (res) => {
          this.photoPath = res.tempImagePath;
          this.cameraing = false; // 拍照完成后隐藏摄像头，显示照片
        },
        fail: (err) => {
          console.error(err);
        }
      });
    },
	// 重新拍照
    retakePhoto() {
      this.cameraing = true; // 重新拍照时显示摄像头，隐藏照片
	  this.photoPath = ''; // 清空照片路径
	  this.$emit('retake');
    },
	// 关闭拍照
    close() {
      this.$emit('close');
    },
	// 上传照片
    uploadPhoto() {
		this.uploading=true;
		$file.uploadImg(this.photoPath).then(img => {
			console.log(img);
			this.uploading=false;
			this.$emit('submit', img.data.url);
		}).catch(e=>{
			this.uploading=false;
		});
    }
  }
};
</script>

<style>
.container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.camera-container, .photo-container {
	position: relative;
	width: 600rpx;
	height: 600rpx;
	overflow: hidden;
}

.camera {
	width: 100%;
	height: 100%;
	/* transform: scaleX(-1); */
}

.circle-overlay {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	border-radius: 50%;
	box-shadow: 0 0 0 9999px rgba(255, 255, 255, 1);
	pointer-events: none; /* 确保遮罩不会影响用户交互 */
}

.photo {
	width: 100%;
	height: 100%;
	/* transform: scaleX(-1); */
}

button {
	margin-top: 30rpx;
}

.error-message {
	color: red;
	font-size: 28rpx;
	margin-bottom: 30rpx;
}
</style>
